package com.karolak.math.view;

import java.awt.GridLayout;
import java.util.LinkedHashMap;
import java.util.Map;

import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
import org.jfree.data.xy.DefaultXYDataset;

public class ChartManager {

	private ChartInd frame;

	private Map<String, ChartPanel> charts;

	public ChartManager(ChartInd frame) {
		this.frame = frame;
		this.charts = new LinkedHashMap<String, ChartPanel>();
	}

	public void addData(String chartName, String seriesName, double[] x, double[] y) {
		double[][] xy = new double[2][];
		xy[0] = x;
		xy[1] = y;
		addData(chartName, seriesName, xy);
	}

	public void addData(String chartName, String seriesName, double[][] xy) {
		ChartPanel chart = getCharts().get(chartName);
		if (chart == null) {
			chart = createChart(chartName);
		}
		XYPlot plot = (XYPlot) chart.getChart().getPlot();
		DefaultXYDataset ds = (DefaultXYDataset) plot.getDataset();
		ds.addSeries(seriesName, xy);
	}

	protected ChartPanel createChart(String name) {
		DefaultXYDataset ds = new DefaultXYDataset();
		XYPlot plot = new XYPlot(ds, new NumberAxis(), new NumberAxis(), new StandardXYItemRenderer());
		plot.getDomainAxis().setAutoRange(true);
		plot.getRangeAxis().setAutoRange(true);
		JFreeChart chart = new JFreeChart(name, plot);
		ChartPanel panel = new ChartPanel(chart);
		getCharts().put(name, panel);
		getFrame().add(panel);
		getFrame().setLayout(new GridLayout(getCharts().size(), 1));
		getFrame().pack();
		return panel;
	}

	// === get/set === //
	public ChartInd getFrame() {
		return frame;
	}

	protected Map<String, ChartPanel> getCharts() {
		return charts;
	}
}
